package cookie

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/url"
	"server/cfg"
	"server/utils/gin_helper"
)

func SetCookie(c *gin.Context, content string, keyPrefix string, maxAgeSecond int64) {
	cookieName := gin_helper.GetClientKey(c, keyPrefix)
	SetCookieCustom(c, cookieName, content, maxAgeSecond)
}

func SetCookieCustom(c *gin.Context, name, content string, maxAgeSecond int64) {
	// 在 Gin 框架中，c.SetCookie() 方法目前（截至 Go 1.21）不直接支持 Partitioned 属性（这是一个较新的 Cookie 属性）。所以需要手动构造 Set-Cookie 头 来添加该属性
	cookieValue := fmt.Sprintf("%s=%s; Max-Age=%d; Path=/; Domain=", name, url.QueryEscape(content), maxAgeSecond)
	cookieValue += fmt.Sprintf("; SameSite=%s", cfg.Config.Cookie.SameSite)
	if cfg.Config.Cookie.Secure {
		cookieValue += "; Secure"
	}
	if cfg.Config.Cookie.HttpOnly {
		cookieValue += "; HttpOnly"
	}
	if cfg.Config.Cookie.Partitioned {
		cookieValue += "; Partitioned"
	}
	c.Header("Set-Cookie", cookieValue)
}

func GetCookie(c *gin.Context, keyPrefix string) (content string, err error) {
	cookieName := gin_helper.GetClientKey(c, keyPrefix)
	content, e := c.Cookie(cookieName)
	if e != nil {
		err = fmt.Errorf("没有名为%s的Cookie：%v", cookieName, e)
	}
	return
}

func DelCookie(c *gin.Context, keyPrefix string) {
	cookieName := gin_helper.GetClientKey(c, keyPrefix)
	c.SetCookie(cookieName, "", -1, "/", "", cfg.Config.Cookie.Secure, cfg.Config.Cookie.HttpOnly)
}
